
#include "shell.h"
#include "job_processing.h"

extern struct sigaction old_action;
extern struct sigaction new_action;
extern job* jobs;
extern int* job_count;
extern int job_shmID;

 
void Init_signal()
{
   
  memset(&new_action, 0, sizeof(new_action));
   
  new_action.sa_sigaction = Sigchld_handler;
   
  new_action.sa_flags = SA_SIGINFO | SA_RESTART;
   
  sigemptyset(&new_action.sa_mask);
   
  sigaction(SIGCHLD, &new_action, &old_action);
   
  signal(SIGTSTP,Sigtstp_handler);
  signal(SIGSTOP,Sigtstp_handler);
}

 
void Sigchld_handler(int sig_no, siginfo_t* info, void* vcontext)
{
   
  pid_t pid = info->si_pid;
  int i;
  int count = *job_count;
   
  for(i=0; i<count; i++){
    if(pid == jobs[i].pid)
      break;
  }
  
   
  if(i < count){
     
    if(jobs[i].type == BG && jobs[i].status == RUN)
      jobs[i].status = DONE;
     
    else if(jobs[i].type == BG && jobs[i].status == SUSPEND);
     
    else
      Del_job(pid);
  }  
}

 
void Sigtstp_handler(int sig_no)
{
   
   
  printf("\n");
  int i;
  int count = *job_count;
  for(i=count - 1; i>0; i--){
    if(jobs[i].type == FG)
      break;
  }
  
  if(i > 0){
     
    jobs[i].status = SUSPEND;
    jobs[i].type = BG;
     
    kill(jobs[i].pid, SIGSTOP);
  }   

}
